package com.hcb.tonguetiphealth.widget.homepage;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hcb.tonguetiphealth.adapter.MemberListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.MemberHomepageActivity;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class MemberListWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "BookOnlineWidget";
	
	private Activity ctx;
	private Handler mHandler;
	private LinearLayout  llBack, llSearch;
	private ListView memberListView;
	private MemberListAdapter memberListAdapter;
	private List<User>memberList;
	private List<User>memberList2;
	private String count = "0";
	
	private String type;
	private String FromWidgetFlag;
	private String keyWord;
	
	private View footerView;
	private TextView tv_footerMore;
	private ProgressBar pb_footerMore;
	
	public MemberListWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		inflate(context, R.layout.homepage_health_member, this); 
		//new BottomWidget(context, this);
		keyWord = ctx.getIntent().getStringExtra("keyWord");
		type = ctx.getIntent().getStringExtra("type");
		FromWidgetFlag = ctx.getIntent().getStringExtra("FromWidgetFlag");
		bindView();
		bindEvent();
		memberList = new ArrayList<User>();
		memberList2 = new ArrayList<User>();
		memberListAdapter = new MemberListAdapter(ctx, memberList2);
		memberListView.setAdapter(memberListAdapter);
		if ("MemberSearchWidget".equals(FromWidgetFlag)) {
			searchMember();
		}else {
			getMember();
		}
	}
	
	private void bindEvent() {

		memberListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				if (arg2 == arg0.getAdapter().getCount() - 1) {
					tv_footerMore
							.setText(R.string.app_list_footer_getting_text);
					pb_footerMore.setVisibility(ProgressBar.VISIBLE);
					if ("MemberSearchWidget".equals(FromWidgetFlag)) {
						searchMember();
					}else {
						getMember();
					}
				} else {
					User member = memberList2.get(arg2);
					Bundle bundle = new Bundle();
					bundle.putSerializable("memeber", member);
					Intent intent = new Intent(ctx,
							MemberHomepageActivity.class);
					intent.putExtras(bundle);
					// ctx.getIntent().putExtra("fromWidgetFlag",
					// "MemberListWidget");
					// ctx.setContentView(new HomepageMemberWidget(ctx));
					ctx.startActivity(intent);
				}
			}
		});
		
		 
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在获取达人列表..");
					break;
				case MessageWhat.DIMISS_DIALOG:
					memberListAdapter.notifyDataSetChanged();
					tv_footerMore.setText(R.string.app_list_footer_more_text);
					pb_footerMore.setVisibility(ProgressBar.GONE);
					dismissMessageDialog();
					break;
				case MessageWhat.NETWORK_FAILD:
					try {
						tv_footerMore.setText(R.string.app_list_footer_more_text);
						pb_footerMore.setVisibility(ProgressBar.GONE);
					  dismissMessageDialog();
					} catch (Exception e) {
						// TODO: handle exception
					}
					//Toast.makeText(ctx,  "网络有点不给力哦", Toast.LENGTH_LONG).show();
					showMessage(ctx, R.string.net_faild);
					break;
				}
			}
		};
 	
	}
	
	private void bindView() {
	
		llBack = (LinearLayout)findViewById(R.id.memberlist_back);
		memberListView = (ListView)findViewById(R.id.member_listview);
		llSearch = (LinearLayout)findViewById(R.id.memberlist_search);
		
		footerView = LayoutInflater.from(ctx).inflate(R.layout.refresh_list_footer, null);
		tv_footerMore = (TextView)footerView.findViewById(R.id.refresh_list_footer_text);
		pb_footerMore = (ProgressBar)footerView.findViewById(R.id.refresh_list_footer_progressbar);
		memberListView.addFooterView(footerView);
		
		llBack.setOnClickListener(this);
		llSearch.setOnClickListener(this);
	}
 
	
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.memberlist_back:
			ctx.finish();
			break;
		case R.id.memberlist_search:
			ctx.setContentView(new MemberSearchWidget(ctx));
			break;
		default:
			break;
		}
	}
	
	private void getMember(){
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		count = memberList.size()+"";
		System.out.println("count:"+count);
		new Thread(){
			public void run() {
				List <NameValuePair> params = new ArrayList <NameValuePair>();
				params.add(new BasicNameValuePair("count",count));
				String result  = HttpUtils.Post(Global.getServlethealthpeople(), params);
				if (Global.DEBUG) {
					System.out.println("result:"+result);
				}
				if (result!=null) {
					parseResponse(result);
					mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
				}else {
					mHandler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);
				}
				
			}
		}.start();
		
	}
	
	private void searchMember() {
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		count = memberList.size() +"";
		new Thread(){
			public void run() {
				List <NameValuePair> params = new ArrayList <NameValuePair>();
				params.add(new BasicNameValuePair("key",keyWord));
				params.add(new BasicNameValuePair("type", type));
				params.add(new BasicNameValuePair("count",count));
				String result  = HttpUtils.Post(Global.getServlethealthpeople(), params);
				if (Global.DEBUG) {
					System.out.println("resultSearch:"+result);
				}
				if (result!=null) {
					parseResponse(result);
					mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
				}else {
					mHandler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);
				}
				
			}
		}.start();
	}
	//解析返回的结果（json）
	private void parseResponse(String result){
		JSONManager jsonManager = new JSONManager();
		boolean success = jsonManager.isGotJSONObject(result);
		if (success) {
			JSONArray jsonArray = jsonManager.getJsonList();
			for(int i=0; jsonArray != null  && i < jsonArray.length(); i++) {
				try {
					User member = new User();
					JSONObject obj = jsonArray.getJSONObject(i);
					member.setUserId(obj.getString("userid"));
					member.setUserName(obj.getString("username"));
					member.setArea(obj.getString("areaname"));
					member.setFans(obj.getString("fans"));
					member.setAttention(obj.getString("attention"));
					member.setSex(obj.getString("gender"));
					String groupId = obj.getString("groupid");
					member.setGroupId(groupId);
					member.setGroupId(groupId);
					
					if (groupId.equals("5")) {//达人（个人）
						member.setImgUrl(obj.getString("headicon"));
						member.setLabels(obj.getString("tags"));
						member.setInfo(obj.getString("intro"));
						member.setLevel(StringUtils.parseFloat(obj.getString("level")));
					}
					else if(groupId.equals("8")) {//达人（商家）
						member.setImgUrl(obj.getString("thumb"));
						member.setLabels(obj.getString("catids"));
						member.setInfo(obj.getString("keyword"));
					}
					if (member.getUserName().equals("haikeyi")) {
						System.out.println("-------"+member.getImgUrl());
						System.out.println("----------"+groupId);
					}
					member.setBirthDayTimeInMillis(1000*StringUtils.parseLong(obj.getString("birthday")));
					member.setHeight(obj.getString("height"));
					member.setWeight(obj.getString("weight"));
					member.setCheckedBody(obj.getString("physical"));
					
//					member.setLevel(level)
					memberList.add(member);
					if (groupId.equals("5") && member.getImgUrl()!=null && !member.getImgUrl().equals("") && !member.getImgUrl().equals("null")) {
						memberList2.add(member);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	@Override
	public void notifyAdapter() {
		
	}
 
	
}
